<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <!-- 其他内容 -->
    <style>
        /* 加载层样式 */
        .loading-overlay {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(255, 255, 255, 0.95);
            display: none;
            justify-content: center;
            align-items: center;
            z-index: 1000;
            flex-direction: column;
            backdrop-filter: blur(3px);
        }

        .spinner {
            width: 50px;
            height: 50px;
            border: 4px solid #f3f3f3;
            border-top: 4px solid #007bff;
            border-radius: 50%;
            animation: spin 1s linear infinite;
        }

        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }

        .loading-text {
            margin-top: 20px;
            color: #333;
            font-size: 1.1em;
            text-align: center;
            max-width: 300px;
            line-height: 1.5;
        }

        .file-list {
            margin-top: 20px;
            border: 1px solid #eee;
            border-radius: 8px;
            padding: 15px;
        }
        .file-item {
            padding: 10px;
            margin: 8px 0;
            border: 1px solid #ddd;
            border-radius: 4px;
            display: flex;
            align-items: center;
            justify-content: space-between;
            transition: background-color 0.2s;
        }
        .file-item:hover {
            background-color: #f9f9f9;
        }
        .preview-link {
            color: #2196F3;
            text-decoration: none;
            margin-right: 15px;
            flex-grow: 1;
        }
        .preview-link:hover {
            text-decoration: underline;
        }
        .file-size {
            color: #666;
            font-size: 0.9em;
        }
        .section-title {
            margin: 20px 0 10px;
            color: #333;
            font-weight: bold;
        }
        #uploadProgress {
            margin: 10px 0;
            height: 5px;
            background-color: #eee;
            display: none;
        }
        #progressBar {
            height: 100%;
            width: 0%;
            background-color: #4CAF50;
            transition: width 0.3s ease;
        }
    </style>
</head>
<body>
    <input type="file" id="uploadInput" multiple>
    <button onclick="handleUpload()">上传文件</button>
     <!-- 新增生成按钮 -->
    <button onclick="handleGenerate()" id="generateBtn">生成Excel报告</button>

    <!-- 加载层 -->

    <div class="loading-overlay" id="loadingOverlay">
        <div class="spinner"></div>
        <div class="loading-text">
            ⏳ 正在生成报告，预计需要3-5分钟...
            <div style="font-size: 0.9em; color: #666; margin-top: 10px;">
                请保持网络畅通，切勿关闭页面
            </div>
        </div>
    </div>

    <!-- 上传进度条 -->
    <div id="uploadProgress">
        <div id="progressBar"></div>
    </div>

    <!-- 已选择文件列表 -->
    <div class="section-title">待上传文件</div>
    <div id="selectedFileList" class="file-list"></div>

    <!-- 已上传文件列表 -->
    <div class="section-title">已上传文件</div>
    <div id="uploadedFileList" class="file-list"></div>


    <script>
        session = ""
        // 初始化时绑定文件选择事件
        document.getElementById('uploadInput').addEventListener('change', function(e) {
            updateSelectedFiles(this.files);
        });

        // 更新已选择文件列表
        function updateSelectedFiles(files) {
            const container = document.getElementById('selectedFileList');
            container.innerHTML = Array.from(files).map(file => `
                <div class="file-item">
                    <span class="file-name">${file.name}</span>
                    <span class="file-size">${formatFileSize(file.size)}</span>
                </div>
            `).join('');
        }

        // 格式化文件大小
        function formatFileSize(bytes) {
            if (bytes === 0) return '0 Bytes';
            const units = ['Bytes', 'KB', 'MB', 'GB'];
            const unitIndex = Math.floor(Math.log(bytes) / Math.log(1024));
            return (bytes / Math.pow(1024, unitIndex)).toFixed(2) + ' ' + units[unitIndex];
        }

        async function handleUpload() {
            const input = document.getElementById('uploadInput');
            const files = input.files;

            if (files.length === 0) {
                alert('请先选择文件');
                return;
            }

            // 显示进度条
            const progressBar = document.getElementById('progressBar');
            document.getElementById('uploadProgress').style.display = 'block';

            const sessionId = generateSessionId();
            session = sessionId
            const formData = new FormData();
            formData.append('session_id', sessionId);

            for (let file of files) {
                formData.append('files', file);
            }

            try {
                const response = await fetch('http://127.0.0.1:8081/api/questionGenerate/fileUpload', {
                    method: 'POST',
                    body: formData,
                });

                const result = await response.json();
               console.log(result);
               console.log(result.status);
               console.log(result.data);
                if (result.status === 'success') {
                    renderUploadedFiles(result.data);
                    input.value = ''; // 清空已选文件
                    document.getElementById('selectedFileList').innerHTML = '';
                }
            } catch (error) {
                console.error('上传失败:', error);
            } finally {
                // 隐藏进度条
                document.getElementById('uploadProgress').style.display = 'none';
                progressBar.style.width = '0%';
            }
        }

        // 渲染已上传文件列表
        function renderUploadedFiles(files) {
            const container = document.getElementById('uploadedFileList');
            container.innerHTML = files.map(file => `
                <div class="file-item">
                    <a href="${file.preview_url}"
                       class="preview-link"
                       target="_blank">
                        ${file.original_name}
                    </a>
                    <span class="file-size">${formatFileSize(file.size)}</span>
                </div>
            `).join('');
        }

        function generateSessionId() {
            return 'session_' + Date.now().toString(36);
        }

        function ganerate() {
            console.log(session)
        }
        async function handleGenerate() {
            const overlay = document.getElementById('loadingOverlay');
            const btn = document.getElementById('generateBtn');

            try {
                // 显示加载层
                overlay.style.display = 'flex';
                btn.disabled = true;

                // 构造请求参数
                const payload = {
                    session_id: session,
                    m_config: {
                        temperature: 0.8,
                        top_p: 0.9,
                        max_tokens: 1000
                    },
                    model: "qwen2.5:14b",
                    stream: "False"
                };

                // 发送请求
                const response = await fetch('http://127.0.0.1:8081/api/questionGenerate/generate', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify(payload)
                });

                // 处理响应
                if (!response.ok) {
                    throw new Error(`请求失败: ${response.status}`);
                }

                // 获取Blob并创建下载链接
                const blob = await response.blob();
                const url = window.URL.createObjectURL(blob);

                // 创建隐藏的下载链接
                const a = document.createElement('a');
                a.style.display = 'none';
                a.href = url;
                a.download = "example.xlsx";  // 使用后端返回的文件名
                document.body.appendChild(a);

                // 触发下载
                a.click();

                // 清理资源
                window.URL.revokeObjectURL(url);
                document.body.removeChild(a);

            } catch (error) {
                console.error('生成失败:', error);
                alert('报告生成失败: ' + error.message);
            } finally {
                // 隐藏加载层
                overlay.style.display = 'none';
                btn.disabled = false;
            }
        }
    </script>
</body>
</html>